package com.cobra.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@RestController
public class DownloadController {
    @RequestMapping("/getCsv")
    public ResponseEntity<InputStreamResource> getCsv(HttpServletRequest request) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("template/featureTemplate.csv");
        InputStreamResource resource = new InputStreamResource(classPathResource.getInputStream());
        String userAgent  = request.getHeader("user-agent").toLowerCase();
        HttpHeaders headers = new HttpHeaders();
        String name = "你好吗.csv";
        String fileName = null;
//        if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
//            // win10 ie edge 浏览器 和其他系统的ie
//            fileName = URLEncoder.encode(name, "UTF-8");
//        } else {
//            // fe
//            fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
//        }
        boolean msBrowser = isMSBrowser(request);
        System.out.println("is IE Browser: "+msBrowser);
        if(msBrowser){
            fileName = URLEncoder.encode(name, "UTF-8");
        }else {
            fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
        }
        //指定文件名
        headers.setContentDispositionFormData("attachment", fileName);
        ResponseEntity<InputStreamResource> body = ResponseEntity.ok()
                .headers(headers)
                .contentLength(classPathResource.contentLength())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
        return body;
    }

    public static boolean isMSBrowser(HttpServletRequest request) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        System.out.println(userAgent);
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal)){
                return true;
            }
        }
        return false;
    }

}
